package com.stefanie.kafkademo.consumer;

import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.annotation.PartitionOffset;
import org.springframework.kafka.annotation.TopicPartition;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.stereotype.Component;

/**
 * @author: stefanie-zy
 * @time: 2023/12/13-15:50
 * @description: kafka消费者
 */
@Component
@Slf4j
public class KafkaConsumer {

    /**
     * @name: 简单——订阅主题组
     * @type: 一次性对多条消息进行处理
     */
    @KafkaListener(topics = "stefanie-zy-topic", groupId = "default-group")
    public void listenGroup(ConsumerRecord<String, String> record, Acknowledgment ack) {
        log.info("主题[stefanie-zy]接收数据：key[{}]；value[{}]；partition:[{}]；offset[{}]", record.key(), record.value(), record.partition(), record.offset());
        // TODO 业务逻辑处理
        // 手动提交情况下执行。不添加消息会被重复消费
        ack.acknowledge();
    }

    /**
     * @name: 复杂——订阅主题组。
     * @description: 消费组[default-group]，默认消费两个主题[stefanie-zy-topic1、stefanie-zy-topic2]。其中stefanie-zy-topic1默认消费分区0、1；stefanie-zy-topic2默认消费分区0，消费分区1的情况下默认从100的偏移量开始消费。concurrency：同组下的消费者个数，并发消费数量，建议小于分区总数
     * @type: 一次对一条消息进行处理
     */
    @KafkaListener(groupId = "default-group", topicPartitions = {
            @TopicPartition(topic = "stefanie-zy-topic1", partitions = {"0", "1"}),
            @TopicPartition(topic = "stefanie-zy-topic2", partitions = "0", partitionOffsets = {@PartitionOffset(partition = "1", initialOffset = "100")})
    }, concurrency = "3")
    public void listenGroupPro(ConsumerRecord<String, String> record, Acknowledgment ack) {
        log.info("主题[stefanie-zy]接收数据：key[{}]；value[{}]；partition:[{}]；offset[{}]", record.key(), record.value(), record.partition(), record.offset());
        // TODO 业务逻辑处理
        // 手动提交情况下执行。不添加消息会被重复消费
        ack.acknowledge();
    }
}
